import { Component, OnInit, trigger, state, style, transition, animate } from '@angular/core';
import { Location }from '@angular/common';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations:[
    trigger('slide',[
      state('shrink', style({ height: '0', overflow: 'hidden', display: 'none' })),
      state('stretch', style({ height: '*', overflow: 'visible', display: 'block' })),
      transition( 'shrink => stretch', animate('300ms') ),
      transition( 'stretch => shrink', animate('300ms') )
    ])
  ]
})

export class AppComponent implements OnInit {
  private menuObject = {};
  private menuTree = [];
  private selectedTopMenu = {};
  private selectedAccordionMenu = {};
  private selectedAccordionSubMenu = {};
  private headers = new Headers({'Content-Type': 'application/json'});

  constructor(
    private location: Location,
    private http: Http,
    private router: Router
  ) { }

  ngOnInit() {

    let path = this.location.path(true);
    console.log(path)
    
    // init menu
    this.http.get('/api/menus').toPromise().then((response) => { 
      let menuArray = response.json();
      let selectedMenuSeq;
      for (let i in menuArray) {
        let menu = menuArray[i];
        menu.state = 'shrink';
        this.menuObject[menu.id] = menu;
        if(menu.funcAction == path) {
          selectedMenuSeq = menu.menuSeq;
        }
      }

      for (let i in menuArray) {
        let menu = menuArray[i];
        let parentId = menu.parentId;

        if(parentId == 0){
          this.menuTree.push(menu);
          continue;
        }

        let parentMenu = this.menuObject[parentId];
        if(!parentMenu.children){
          parentMenu.children = [];
        }
        parentMenu.children.push(menu);
      }

      if(selectedMenuSeq) {
        let menuArr = selectedMenuSeq.split('-');
        this.selectedTopMenu = this.menuObject[menuArr[0]];
        this.selectedAccordionMenu = this.menuObject[menuArr[1]];
        this.selectedAccordionSubMenu = this.menuObject[menuArr[2]];
        this.selectedAccordionMenu['state'] = 'stretch';
      } else {
        this.selectedTopMenu = this.menuTree[0];
      }
    });
  }

  selectTopMenu(menu) {
    this.selectedTopMenu = menu;
  }

  selectAccordionMenu(menu){
    menu.state=menu.state=='stretch'?'shrink':'stretch';
  }

  selectAccordionSubMenu(menu){
    this.selectedAccordionSubMenu=menu;
    this.selectedAccordionMenu = this.menuObject[menu.parentId];
  }
}
